package cn.getech.data.metadata.model.excel;

import cn.getech.data.metadata.utils.MapUtils;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.Map;
/**
 * @description: excel 各属性添加枚举值
 * @author: wangzhaowen：kiss
 * @create: 2020/10/17 16:00
 * @version: 2020/10/17
 **/
@Slf4j
public class MySheetWriteHandler implements SheetWriteHandler {

    private  Map<Integer, String[]> explicitListConstraintMap;

    public MySheetWriteHandler(Class dataClass) {
        explicitListConstraintMap = MapUtils.explicitSource(dataClass);
    }
    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        DataValidationHelper helper = sheet.getDataValidationHelper();
        explicitListConstraintMap.forEach((k, v) -> {
            CellRangeAddressList rangeList = new CellRangeAddressList();
            CellRangeAddress addr = new CellRangeAddress(1, 1000, k, k);
            rangeList.addCellRangeAddress(addr);
            DataValidationConstraint constraint = helper.createExplicitListConstraint(v);
            DataValidation validation = helper.createValidation(constraint, rangeList);
            sheet.addValidationData(validation);
        });
    }
}
